package com.ui.basic.security.realm;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsecurity.authc.AuthenticationException;
import org.jsecurity.authc.AuthenticationInfo;
import org.jsecurity.authc.AuthenticationToken;
import org.jsecurity.authc.UsernamePasswordToken;
import org.jsecurity.authz.AuthorizationInfo;
import org.jsecurity.realm.AuthorizingRealm;
import org.jsecurity.subject.PrincipalCollection;
import org.springframework.beans.factory.InitializingBean;

import com.ui.basic.security.service.JSecurityService;

public class DefaultRealm extends AuthorizingRealm implements InitializingBean {
	protected transient final Log log = LogFactory.getLog(getClass());

	protected JSecurityService jSecurityService = null;

	public DefaultRealm() {
		setName("DefaultRealm");
	}

	public void setJSecurityService(JSecurityService securityService) {
		jSecurityService = securityService;
	}

	public void afterPropertiesSet() throws Exception {
		if (this.jSecurityService == null) {
			throw new IllegalStateException(
					"securityService property was not injected.  Please check your Spring config.");
		}
	}

	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		log
				.debug(">>>>DefaultRealm.doGetAuthenticationInfo(AuthenticationToken authcToken)");
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		return jSecurityService.findUserSecurity(token.getUsername());
	}

	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		log
				.debug(">>>>DefaultRealm.doGetAuthorizationInfo(PrincipalCollection principals)");
		Long userId = (Long) principals.fromRealm(getName()).iterator().next();
		return jSecurityService.getUserSecurity(userId);
	}
}
